package com.ksyun.start.camp.service.impl;

import com.ksyun.start.camp.model.ApiResponse;
import com.ksyun.start.camp.model.LogInstance;
import com.ksyun.start.camp.service.LoggingService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.*;

/**
 * 日志服务的实现
 */
@Component
public class LoggingServiceImpl implements LoggingService {

    private final Map<String, List<LogInstance>> logStorage = new HashMap<>();
    private int currentLogId = 0;

    public ApiResponse log(LogInstance logInfo) {

        String serviceId = logInfo.getServiceId();
        if (!logStorage.containsKey(serviceId)) {
            logStorage.put(serviceId, new ArrayList<>());
        }

        List<LogInstance> logInstances = logStorage.get(serviceId);

        // 检查日志消息是否已存在于列表中
        boolean isDuplicate = false;
        for (LogInstance existingLog : logInstances) {
            if (areLogInstancesEqual(logInfo, existingLog)) {
                isDuplicate = true;
                break;
            }
        }
        if (!isDuplicate) {//没有重复
            // 假设logId是自增的
            if(logInfo.getLogId()==null||logInfo.getLogId()==0){
                logInfo.setLogId(++currentLogId);
            }
            logInstances.add(logInfo);
            return new ApiResponse(200, "日志记录已保存");
        } else {
            return new ApiResponse(200, "重复日志，已忽略");
        }
    }

    // 辅助方法，用于比较两个 LogInstance 对象是否相同（考虑所有字段）
    private boolean areLogInstancesEqual(LogInstance log1, LogInstance log2) {
        return log1.getServiceName().equals(log2.getServiceName()) &&
                log1.getServiceId().equals(log2.getServiceId()) &&
                log1.getDatetime().equals(log2.getDatetime()) &&
                log1.getLevel().equals(log2.getLevel()) &&
                log1.getMessage().equals(log2.getMessage());
    }

    public ApiResponse<List<LogInstance>> getLogs(String service) {
        if (StringUtils.isEmpty(service)) { //service为空，倒序返回所有服务名对应的所有日志
            List<LogInstance> allLogs=new ArrayList<>();
            for (List<LogInstance> logInstances :logStorage.values()) {
                allLogs.addAll(logInstances);
            }
            // 按logId倒序排列
            allLogs.sort(Comparator.comparingInt(LogInstance::getLogId).reversed());
            return new ApiResponse<List<LogInstance>>(200,allLogs);
        }
        //service不为空时，返回对应服务id的日志
        //得到该服务名所对应的日志
        List<LogInstance> filteredLogs = logStorage.get(service);
        // 只返回最后5条记录
        // 判断是否还有5条数据
        int size = filteredLogs.size();
        List<LogInstance> last5Logs=new ArrayList<>();
        if(size<=5){
            last5Logs = filteredLogs.subList(0, size);
        }else{
            last5Logs = filteredLogs.subList(size-5,size);
        }
        // 按logId倒序排列
        last5Logs.sort(Comparator.comparingInt(LogInstance::getLogId).reversed());
        return new ApiResponse<List<LogInstance>>(200,last5Logs);
    }
}
